const path = require("path");
const { promisify } = require("util");

const download = promisify(require("download-git-repo"));

const { vueRepo, isGitClone, vueRepoZip } = require("../config/repo-config.js");

const { commandSpawn } = require("../utils/terminal.js");
const { compile, writeToFile, createDirSync } = require("../utils/utils.js");

/**
 * 创建项目的acitons
 *  * @param {string} project 项目名称
 */
const createProjectActions = async (project) => {
  console.log("");
  console.log("开始创建");
  console.log("");

  //克隆项目模板
  await download(vueRepoZip, project);
  console.log("创建成功 正在下载依赖");

  //下载项目依赖
  await commandSpawn(
    process.platform === "win32" ? "npm.cmd" : "npm",
    ["install"],
    { cwd: `./${project}` }
  );
  console.log("依赖下载完成 正在打开项目");

  commandSpawn(
    process.platform === "win32" ? "npm.cmd" : "npm",
    ["run", "dev"],
    { cwd: `./${project}` }
  );

  return Promise.resolve();
};

/**
 *创建组件的actions
 * @param {string} comName 组件名称
 */
const createComponentsActions = async (comName, dest) => {
  const result = await compile("vue-components.ejs", {
    name: comName,
    lowerName: comName.toLowerCase(),
  });
  console.log("result", result);
  let targetPath = path.resolve(dest, `${comName}Com.vue`);
  writeToFile(targetPath, result);
};

/**
 *创建页面的actions
 * @param {string} pagename 页面名称
 */
const createViewsAndRouterActions = async (pagename, dest) => {
  const pageResult = await compile("vue-views.ejs", {
    name: pagename,
    lowerName: pagename.toLowerCase(),
  });
  const routeResult = await compile("vue-router.ejs", {
    name: pagename,
    lowerName: pagename.toLowerCase(),
  });
  if (createDirSync(dest + `/${pagename}`)) {
    let targetPath = path.resolve(dest + `/${pagename}`, `${pagename}View.vue`);
    writeToFile(targetPath, pageResult);
  }
};

/**
 *创建路由的actions
 * @param {string} routerName 路由名称
 */
const createRoutersActions = async (routerName, dest) => {
  // const result = await compile("vue-views.ejs", {
  //   name: routerName,
  //   lowerName: routerName.toLowerCase(),
  // });
  // let targetPath = path.resolve(dest, `${routerName}View.vue`);
  // writeToFile(targetPath, result);
};

module.exports = {
  createProjectActions,
  createComponentsActions,
  createViewsAndRouterActions,
  createRoutersActions,
};
